<?php
/**
 * Review
 *
 * Обработка данных отзывов
 *
 * @author Mike
 */
class Review extends ActiveRecord  {
	protected $tableName = 'review';
	public $pkName = 'ID_review';
	
	protected $arrSettings = array('created_at' => true, 'author' => true, 'updated_at' => true);

	public $validatesLengthOf = array(
			'review_text' => array('min' => 2, 'max' => 2000, 'message' => 'Текст - 2-2000 симоволов')
	);
	
	public $validatesFormatOf = array(
			'score' => array('with' => '#^[1-5]{1}$#', 'message' => 'Неверный формат оценки')
	);
	
	protected function afterCreate() {
		$objDB = Service_Database::instanse();
		
		//Пересчитываем среднюю оценку товара и сохраняем её
		$stmt = "SELECT AVG(`review`.`score`) FROM review WHERE `review`.`ID_product`='" . $this->getField('ID_product') . "'";
		$avgScore = round($objDB->selectOneValue($stmt), 2);
		
		$stmt = "UPDATE `product` SET `product`.`reviews_score`='" . $avgScore . "' WHERE `product`.`ID_product`='" . $this->getField('ID_product') . "'" ;
		$objDB->query($stmt);
	}
}